package cn.lb.framework.poi.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取唯一ID工具类
 * Created by Administrator on 2016/4/26.
 */
public final class ImageUtil {

	private static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);

	public static byte[] compressPictures(String filePath,int width,int heigh) throws IOException{
		byte[] file_byte=null;
		if(StringUtils.isNotBlank(filePath)){
			ByteArrayOutputStream bos=null;
			InputStream iss=null;
			try{
					File f = new File(filePath);
					if(f.exists()){
						logger.info("==========文件存在！");
					}else{
						logger.info("==========文件不存在！" + filePath);
					}
					try{
						//绘制缩略图
						iss = new FileInputStream(f); ;
			            BufferedImage src = ImageIO.read(iss); // 读入文件  
				    	int newwidths = width;
				    	int newheight = heigh;
			            Image image = src.getScaledInstance(newwidths, newheight, Image.SCALE_DEFAULT);  
			            BufferedImage tag = new BufferedImage(newwidths, newheight, BufferedImage.TYPE_INT_RGB);
			            Graphics g = tag.getGraphics(); 
			            g.drawImage(image, 0, 0, null); // 绘制缩小后的图  
			            g.dispose();  
			            bos = new ByteArrayOutputStream();
						ImageIO.write(tag, "jpg", bos);// 输出到文件流
					    file_byte = bos.toByteArray();
						
					}catch(Exception e){
						e.printStackTrace();
					}finally{
						if(null != bos){
							bos.close();
							bos = null;
						}
					} 
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(null != iss){
					iss.close();
					iss = null;
				}
			} 
			return file_byte;
		}
      return null;
	}
}
